<template>
  <div>
    <el-card class="box-card" style="margin:20px">
      <div slot="header" class="clearfix">
        <el-form ref="form" :model="params" :inline="true" label-position="right" label-width="80px">
          <!-- <el-row>
            <el-col :span="5"> -->
          <el-form-item label="系统">
            <el-select v-model="params.tenantId" placeholder="请选择" @change="getFlowList">
              <el-option
                v-for="item in systemList"
                :key="item.id"
                style="width:100%"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- </el-col> -->
          <!-- <el-col :span="5"> -->
          <el-form-item label="名称">
            <el-input v-model="params.name" placeholder="输入名称" />
          </el-form-item>
          <!-- </el-col>
            <el-col :span="5"> -->
          <el-form-item label="实例id">
            <el-input v-model="params.id" placeholder="输入实例id" />
          </el-form-item>
          <!-- </el-col>
            <el-col :span="9"> -->
          <el-form-item label="流程日期">
            <el-date-picker
              v-model="processTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <!-- </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="5"> -->
          <el-form-item label="用户">
            <el-input v-model="loginname" placeholder="用户" />
          </el-form-item>
          <!-- </el-col>
            <el-col :span="6"> -->
          <el-form-item label="待办已办">
            <el-select v-model="isdone" placeholder="请选择">
              <el-option style="width:100%" :value="1" label="已办" />
              <el-option style="width:100%" :value="0" label="待办" />

            </el-select>
            <!-- <el-input v-model="isdone" placeholder="1已办0待办" /> -->
          </el-form-item>
          <!-- </el-col>
            <el-col :span="6"> -->
          <el-form-item label="变量名称">
            <el-input v-model="varname" placeholder="变量名称" />
          </el-form-item>
          <!-- </el-col> -->
          <!-- <el-col :span="5"> -->
          <el-form-item label="变量值">
            <el-input v-model="varvalue" placeholder="变量值" />
          </el-form-item>
          <!-- </el-col> -->
          <!-- <el-col :span="4"> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getFlowList">查询</el-button>
          </el-form-item>
          <!-- </el-col>
            <el-col :span="4"> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="batchDelete(tableChecked)">批量删除</el-button>
          </el-form-item>
          <!-- </el-col>
          </el-row> -->
        </el-form>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column
          align="center"
          type="selection"
          width="55"
        />
        <el-table-column
          fixed
          prop="id"
          label="实例id"
          min-width="30%"
        />
        <el-table-column
          fixed
          prop="processDefinitionName"
          label="模型名称"
          min-width="30%"
        />
        <el-table-column
          fixed
          prop="processDefinitionKey"
          label="模型ID"
          min-width="30%"
        />
        <el-table-column
          fixed
          prop="deploymentId"
          label="部署id"
          min-width="20%"
        />
        <el-table-column
          fixed
          prop="tenantId"
          label="系统Id"
          min-width="20%"
          :formatter="formatStatus"
        />
        <el-table-column
          fixed
          prop="startTime"
          label="创建时间"
          min-width="30%"
        />
        <!-- <el-table-column
          fixed
          prop="endTime"
          label="结束时间"
          min-width="30%"
        />-->
        <!-- <el-table-column
          fixed
          align="center"
          label="修改人员"
          prop="startTime"
          min-width="30%"
        /> -->
        <el-table-column
          fixed
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="danger"
              icon="el-icon-edit"
              @click="updateProcess(scope.$index, scope.row)"
            >
              修改
            </el-button> -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteProcess(scope.$index, scope.row)"
            >
              删除
            </el-button>
            <el-button
              size="mini"
              type="info"
              icon="el-icon-picture-outline"
              @click="viewProcessImage(scope.$index,scope.row)"
            >
              查看流程图
            </el-button>
            <el-button
              size="mini"
              type="info"
              icon="el-icon-s-unfold"
              @click="getTaskList(scope.row)"
            >
              任务列表
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float:right;margin:20px">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog
      title="流程任务"
      :fullscreen="fullscreen"
      :visible.sync="dialogVisible"
      append-to-body
      center
    >
      <el-table v-loading="loading" :data="taskData" style="width: 100%">
        <el-table-column
          fixed
          prop="id"
          label="任务id"
          min-width="30%"
        />
        <el-table-column
          fixed
          prop="name"
          label="任务名称"
          min-width="30%"
        />
        <el-table-column
          fixed
          prop="assignee"
          label="代理人"
          min-width="30%"
        />
        <el-table-column
          fixed
          prop="candidate"
          label="候选人"
          min-width="30%"
        />
        <el-table-column
          prop="taskType"
          label="已/待办"
          width="100"
          :filters="[{ text: '待办', value: 0 }, { text: '已办', value: 1 }]"
          :filter-method="filterTask"
          filter-placement="bottom-end"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.taskType === 0 ? 'primary' : 'success'"
              disable-transitions
            >{{ formatterTaskType(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-position"
              @click="changeTask(scope.$index, scope.row)"
            >
              转交
            </el-button>
            <el-button
              size="mini"
              type="info"
              icon="el-icon-eye"
              @click="viewPropertes(scope.$index, scope.row)"
            >
              查看自定义属性
            </el-button>
            <el-button
              size="mini"
              type="info"
              icon="el-icon-eye"
              @click="viewVariables(scope.$index, scope.row)"
            >
              查看变量
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      title="任务自定义属性"
      :visible.sync="propertiesDialogVisible"
      append-to-body
      center
    >
      <el-table :data="propertiesData" style="width: 100%">
        <el-table-column
          fixed
          prop="key"
          label="属性名"
          min-width="30%"
        />
        <el-table-column
          fixed
          prop="value"
          label="属性值"
          min-width="60%"
        />
      </el-table>
    </el-dialog>
    <el-dialog
      title="任务变量"
      :visible.sync="variablesDialogVisible"
      append-to-body
      center
    >
      <el-table v-loading="loading" :data="taskVariables" style="width: 100%">
        <el-table-column
          fixed
          prop="name"
          label="变量名"
          min-width="30%"
        />
        <el-table-column
          fixed
          prop="cachedValue"
          label="变量值"
          min-width="60%"
        />
      </el-table>
    </el-dialog>
    <el-dialog
      title="流程图"
      :fullscreen="fullscreen"
      :visible.sync="processImageDialogVisible"
      append-to-body
      center
    >
      <div v-html="processImageData" />
    </el-dialog>
    <el-dialog
      title="删除原因"
      :visible.sync="processDeleteDialogVisible"
      append-to-body
      center
    >
      <el-input v-model="processDeleteReason" placeholder="请输入删除原因" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDelete">取 消</el-button>
        <el-button type="primary" @click="doDeleteProcess">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="新的办理人员"
      :visible.sync="updateDialogVisible"
      append-to-body
      center
    >
      <el-input v-model="processUpdatePersion" placeholder="请输入新的办理人员" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelprocess">取 消</el-button>
        <el-button type="primary" @click="updateInsProcess(scope.$index, scope.row)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="设置流程人员"
      :visible.sync="taskUserDialogVisible"
      append-to-body
      center
    >
      <el-input v-model="taskUserData" placeholder="请输入要转交的人，多个人用英文的逗号隔开" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelChange">取 消</el-button>
        <el-button type="primary" @click="doChangeTask">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      params: { },
      systemList: [],
      fullscreen: true,
      dialogVisible: false,
      taskData: [],
      propertiesDialogVisible: false,
      propertiesData: {},
      variablesDialogVisible: false,
      taskVariables: [],
      processImageDialogVisible: false,
      processImageData: '',
      processDeleteDialogVisible: false,
      processDeleteReason: '',
      processDeleteId: 0,
      taskUserDialogVisible: false,
      changeUserTask: {},
      taskUserData: '',
      processTime: [],
      loginname: '',
      isdone: '',
      varvalue: '',
      varname: '',
      tableChecked: [],
      updateDialogVisible: false,
      processUpdatePersion: ''
    }
  },
  mounted() {
    this.getAuthSystemId()
  },
  methods: {
    getAuthSystemId() {
      const that = this
      this.$axios.get(this.basePortalUrl + '/user/systemList')
        .then(res => {
          if (res || res.data) {
            that.systemList = res.data.data
            if (that.systemList && that.systemList.length > 0) {
              that.params.tenantId = that.systemList[0].id
              that.getFlowList()
            } else {
              this.$message.error('权限不足，没有可查询的业务系统')
            }
          } else {
            this.$message.error('权限不足，没有可查询的业务系统')
          }
        }).catch((e) => { console.error(e) })
    },
    getFlowList() {
      if (this.params.tenantId) {
        const that = this
        this.params.current = this.currentPage
        this.params.pageSize = this.pageSize
        this.params.loginname = this.loginname
        this.params.isdone = this.isdone
        this.params.varvalue = this.varvalue
        this.params.varname = this.varname
        if (this.processTime) {
          this.params.startTime = this.processTime[0]
          this.params.endTime = this.processTime[1]
        } else {
          this.params.startTime = ''
          this.params.endTime = ''
        }

        this.$axios.get(this.baseFlowUrl + '/process/getProcessInstances/' + this.params.tenantId, { params: this.params })
          .then(res => {
            that.loading = false
            if (res || res.data) {
              that.tableData = res.data.data.records
              that.total = parseInt(res.data.data.total)
            }
          }).catch((e) => {
            that.loading = false
            console.error(e)
          })
      } else {
        this.$message.warning('请选择一个业务系统')
      }
    },
    handleSelectionChange(val) {
      // var _this = this
      console.log('handlee--', val)
      this.tableChecked = val
      // console.log('tableChecked--', tableChecked)
    },
    batchDelete(row) {
      if (this.tableChecked.length) { // 当前选中数量不为0时执行下一步
        const processInstanceId = this.tableChecked.map(item => item.id).join(',')// 选中的id调用批量删除接口时，用逗号连接，也可以是其他形式，具体的按照接口要求来，这边以逗号连接为例
        console.log(processInstanceId)
        this.$axios.delete(this.baseFlowUrl + '/process/deleteAllProcessInstance/' + processInstanceId).then(() => {
          this.tableData.map((item, index) => { // 遍历删除已选数据
            this.tableChecked.map((subItem) => {
              if (subItem.id - 0 === item.id - 0) {
                this.tableData.splice(index, 1)
              }
            })
          })
          this.tableChecked = []
        })
      }
    },
    getTaskList(row) {
      if (row) {
        const that = this
        this.$axios.get(this.baseFlowUrl + '/task/getTasksByProcessInstanceId/' + row.tenantId + '/' + row.id)
          .then(res => {
            that.loading = false
            if (res || res.data) {
              that.taskData = res.data.data
              that.dialogVisible = true
            }
          }).catch((e) => {
            that.loading = false
            console.error(e)
          })
      } else {
        this.$message.warning('请选择一个流程')
      }
    },
    formatStatus(row, column, cellValue, index) {
      if (this.systemList) {
        const sys = this.systemList.filter(item => {
          return row.tenantId === item.id
        })
        if (sys && sys.length > 0) {
          return sys[0].name
        } else {
          return '未知'
        }
      } else {
        return '未知'
      }
    },
    formatterTaskType(row) {
      if (row.taskType === 0) {
        return '待办'
      } else if (row.taskType === 1) {
        return '已办'
      } else {
        return '未知'
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getFlowList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getFlowList()
    },
    deleteProcess(index, row) {
      if (row) {
        this.processDeleteDialogVisible = true
        this.processDeleteId = row.id
      } else {
        this.$message.warning('请选择一个流程')
      }
    },
    cancelDelete() {
      this.processDeleteDialogVisible = false
    },
    cancelprocess() {
      this.updateDialogVisible = false
    },
    updateInsProcess(index, row) {
      if (!this.processUpdatePersion) {
        this.$message.warning('请输入新的办理人员')
        return
      }
      // this.$axios.get(this.baseFlowUrl + '/process/updateProcessInstanceId/' + row.id + '?tenantId=' + row.tenantId + '?UpdatePersion =' + UpdatePersion)
    },
    doDeleteProcess() {
      if (!this.processDeleteReason) {
        this.$message.warning('请输入删除原因')
        return
      }
      const that = this
      this.$axios.delete(this.baseFlowUrl + '/process/deleteProcessInstance/' + this.processDeleteId, { params: { reason: this.processDeleteReason }})
        .then(res => {
          that.loading = false
          if (res || res.data) {
            that.getFlowList()
          }
          this.processDeleteDialogVisible = false
        }).catch((e) => {
          that.loading = false
          console.error(e)
        })
    },
    filterTask(value, row) {
      return row.taskType === value
    },
    cancelChange() {
      this.taskUserDialogVisible = false
    },
    changeTask(index, row) {
      if (row) {
        if (row.taskType === 1) {
          this.$message.warning('任务已完成，不可转交')
          return
        }
        this.taskUserDialogVisible = true
        this.changeUserTask = row
      } else {
        this.$message.warning('请选择一个流程')
      }
    },
    doChangeTask() {
      if (!this.taskUserData) {
        this.$message.warning('请填写要转交的人，多个人用英文的逗号隔开')
        return
      }
      const that = this
      this.$axios.post(this.baseFlowUrl + '/task/returnOrTransferTask?taskId=' + this.changeUserTask.id + '&assignee=' + this.taskUserData)
        .then(res => {
          that.loading = false
          if (res || res.data) {
            that.getTaskList({ id: that.changeUserTask.processInstanceId, tenantId: that.changeUserTask.tenantId })
          }
        }).catch((e) => {
          that.loading = false
          console.error(e)
        })
    },
    updateProcess(index, row) {
      if (row) {
        this.$axios.get(this.baseFlowUrl + '/process/getProcessInstanceId/' + row.id + '?tenantId=' + row.tenantId)
          .then(res => {
            if (res || res.data) {
              const assignee = res.data.data
              this.$confirm('当前审批人是' + assignee + ',是否确认修改', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'

              }).then(() => {
                this.updateDialogVisible = true
              })
            }
          })
      }
    },
    viewProcessImage(index, row) {
      if (row) {
        const that = this
        this.$axios.get(this.baseFlowUrl + '/process/getImageByProcessInstanceId/' + row.id + '?tenantId=' + row.tenantId)
          .then(res => {
            that.loading = false
            if (res || res.data) {
              console.log(res.data)
              that.processImageData = res.data
              that.processImageDialogVisible = true
            }
          }).catch((e) => {
            that.loading = false
            console.error(e)
          })
      } else {
        this.$message.warning('请选择一个流程')
      }
    },
    viewPropertes(index, row) {
      this.propertiesDialogVisible = true
      const temp = []
      for (const key in row.properties) {
        temp.push({ key: key, value: row.properties[key] })
      }
      this.propertiesData = temp
    },
    viewVariables(index, row) {
      this.variablesDialogVisible = true
      this.taskVariables = row.historyVariables
    }
  }
}
</script>
<style  scoped>
   .el-form-item{
    margin-bottom: 10px;
  }
  .el-input{
    width: 200px;
  }
</style>
